<template>
  <div>
    <el-drawer
      :visible.sync="drawerVisible"
      size="30%"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :append-to-body="true"
      :with-header="false"
      :wrapper-closable="false"
    >
      <el-container>
        <el-header> <div>编辑{{ flowInstances.CustomName }}</div> </el-header>
        <el-tabs type="card">
          <el-tab-pane label="单据信息">
            <el-main class="edit-form main-full-height">
              <el-form ref="dataForm" label-width="100px" :model="flowInstances" label-position="right">
                <el-form-item label="标题" prop="CustomName" :rules="[{ required: true, message: '标题必填', trigger: 'blur' }]">
                  <el-input v-model="flowInstances.CustomName" />
                </el-form-item>
              </el-form>
              <CreatedForm v-if="createdFormData.list && createdFormData.list.length > 0 && drawerVisible" ref="createdForm" insite="true" :data="createdFormData" :value.sync="formValue" :remote="remoteFuncs" />
            </el-main>
          </el-tab-pane>
          <el-tab-pane label="审批流程">
            <el-main class="edit-form main-full-height">
              <div class="main padding-tb-sm">
                <el-timeline>
                  <el-timeline-item
                    v-for="(activity, index) in activities"
                    :key="index"
                    :icon="activity.icon"
                    :type="activity.type"
                    :color="activity.color"
                    :size="activity.size"
                    :timestamp="activity.timestamp"
                    placement="top"
                  >
                    <div class="data-log">
                      <div class="flex-between padding-tb-sm">
                        <div>
                          <span class="bold padding-lr-sm">{{ activity.NodeName }}</span>
                          <span class="blue bold padding-lr"> {{ activity.CreateUserName }} </span>
                          {{ activity.OperationType!=1?activity.OpinionDesc:"" }}
                        </div>

                      </div>
                      <div class="flex-between">
                        <div>
                          <span class="text-sm ">{{ activity.Content }} {{ activity.OperationType==9?"  说明:"+activity.Remark:"" }}</span>
                        </div>
                        <div />
                      </div>
                      <div v-if="activity.OperationType!=9">
                        <div v-for="com in activity.comments" :key="com.Id" class="bg-grey light text-sm padding-lr  radius margin-top">
                          <div class="comment-item padding-tb-sm">
                            <div class="flex-start">
                              <div> <span class="text-bold">{{ com.CreateUserName }}</span> 的评论 </div>
                              <div class="margin-left"> {{ com.CreateTime }}</div>
                            </div>
                            <div class="margin-top-sm">
                              {{ com.Content }}
                            </div>
                            <div class="flex-start flex-wrap margin-top-sm">
                              提醒关注：
                              <el-tag v-for="u in com.Users" :key="u.Id" :hit="false" size="mini" class="margin-xs">@{{ u.Name }} </el-tag>
                            </div>
                            <div v-if="com.Attachment" class="margin-top-sm">
                              <Upload :data="JSON.parse(com.Attachment)" :action="uploadUrl" :disabled="true" />
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-timeline-item>
                  <el-timeline-item v-if="flowInstances.InstanceResult ===1">
                    {{ flowInstances.ActivityName }}(审批中)
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-main>
          </el-tab-pane>
        </el-tabs>
        <el-footer style="height:auto;min-height:60px">
          <div>
            <el-button
              size="medium"
              @click="onCancel"
            >返回</el-button>
            <el-button
              type="primary"
              size="medium"
              plain
              @click="onSubmit(0)"
            >保存草稿</el-button>
            <el-button
              type="primary"
              size="medium"
              @click="onSubmit(1)"
            >提交</el-button>
          </div>
        </el-footer>
      </el-container>
    </el-drawer>
    <el-dialog
      title="选择审批人"
      :visible.sync="dialogVisible"
      width="500px"

      :show-close="false"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-container>
        <el-main class="main-dialog">
          <div class=" text-normal ">领导审批<span class="margin-left gray light">2人及以上或签</span></div>
          <div class="flex-start ">
            <div
              v-for="item in selectUser"
              :key="item.Id"
              class="text-center black light text-normal"
            >
              <div class="avater bg-grey">
                <i class="el-icon-user-solid text-xxxl padding-top-sm white" />
              </div>
              {{ item.Name }}
            </div>

            <div class="text-center" @click="selectApprove">
              <div class="avater bg-blue">
                <i class="el-icon-plus text-xxxl padding-top-sm" />
              </div>
              请选择
            </div>

          </div>
        </el-main>
        <el-footer>
          <div>
            <!-- <el-button
              size="medium"
              @click="selectApprove"
            >选择审批人</el-button> -->
            <el-button
              size="medium"
              type="primary"
              @click="dialogVisible=false,customVerifiy()"
            >提交</el-button>
          </div>
        </el-footer>
      </el-container>
    </el-dialog>
    <el-dialog title="选择人员" :visible.sync="approverRoleVisible" width="600px" append-to-body class="promoter_person">
      <el-container>
        <el-main class="flex">
          <div class="person_tree l">
            <ul>
              <li
                v-for="item in userSource"
                :key="item.Id"
                class="check_box not"
                :class="toggleClass(selectUser,item,'Id')&&'active'"
                @click="selectUser=[item]"
              >
                <a :title="item.Name"><img src="@/assets/images/icon_role.png">{{ item.Name }}</a>
              </li>
            </ul>
          </div>
          <div class="has_selected l">
            <p class="clear">已选（{{ selectUser.length }}）
              <a @click="selectUser=[]">清空</a>
            </p>
            <ul>
              <li v-for="item in selectUser" :key="item.Id">
                <img src="@/assets/images/icon_role.png">
                <span>{{ item.Name }}</span>
                <img src="@/assets/images/cancel.png" @click="removeEle(selectUser,item,'Id')">
              </li>
            </ul>
          </div>
        </el-main>
        <el-footer class="demo-drawer__footer clear">
          <div>
            <el-button @click="approverRoleVisible = false">返回</el-button>
            <el-button type="primary" @click="approverRoleVisible = false">确定</el-button>
          </div>
        </el-footer>
      </el-container>
    </el-dialog>
    <selectPerson ref="selectPersonDialog" :echo-list="selectUser" @allSelect="chooseUser" />
  </div>
</template>
<script>
import selectPerson from '@/views/components/permissions/selectperson'
import CreatedForm from '@/components/flowset/Formcreated/components/CreatedForm'
import { saveFlowInstancesForUpadate, customVerifiy, getComment, queryHistories } from '@/api/flow/index'
import { getUnitProject } from '@/api/project/project'
export default {
  components: {
    CreatedForm,
    selectPerson
  },
  // eslint-disable-next-line vue/require-prop-types
  props: ['flowInstances'],
  data() {
    return {
      drawerVisible: false,
      dialogVisible: false,
      activities: [],
      approverRoleVisible: false,
      userSource: [],
      selectUser: [],
      selfselection: '',
      formValue: {},
      instance: {},
      remoteFuncs: {
        searchProject(resolve) {
          getUnitProject().then(res => {
            resolve(res.Data)
          }).catch(re => {
          })
        }
      }
    }
  },
  computed: {
    createdFormData() {
      var oo = { list: [], config: {}}
      if (this.flowInstances && this.flowInstances.FormContent) {
        oo.list = JSON.parse(this.flowInstances.FormContent)
        var currColnumsPermission = JSON.parse(this.flowInstances.CurrColnumPermission)
        oo.list.forEach(item => {
          item.options.disabled = true
        })
      }
      return oo
    }
    // formValue() {
    //   var defaultv = {}
    //   if (this.flowInstances && this.flowInstances.FormData) {
    //     defaultv = JSON.parse(this.flowInstances.FormData)
    //   }
    //   return defaultv
    // }
  },
  watch: {
    flowInstances: {
      deep: true,
      handler(val) {
        var defaultv = {}
        if (this.flowInstances && this.flowInstances.FormData) {
          defaultv = JSON.parse(this.flowInstances.FormData)
        }
        this.formValue = defaultv
        this.queryHistoriesData(val.Id)
      }
    }
  },
  methods: {
    queryHistoriesData(id) {
      this.activities = []
      queryHistories(id).then(res => {
        getComment(id).then(com => {
          res.Data.forEach(item => {
            this.activities.push({
              CreateUserName: item.CreateUserName,
              Opinion: item.Opinion,
              OperationType: item.OperationType,
              Content: item.Content,
              OpinionDesc: item.OpinionDesc,
              Remark: item.Remark,
              timestamp: item.CreateTime,
              NodeName: item.NodeName,
              comments: com.Data.filter(o => o.CommentNodeId === item.NodeId) || [],
              size: 'large',
              type: 'primary',
              icon: 'el-icon-success'
            })
          })
        })
      })
    },
    showBillDrawer() {
      this.drawerVisible = true
      this.selectUser = []
      this.userSource = []
      this.selfselection = ''
    },
    onCancel() {
      this.drawerVisible = false
    },
    onSubmit(t) {
      var _this = this
      _this.$refs['dataForm'].validate(valid => {
        if (valid) {
          _this.$refs.createdForm.getData().then(res => {
            var userIds = []
            _this.selectUser.forEach(item => {
              userIds.push(item.Id)
            })
            var instance = {
              Id: _this.flowInstances.Id,
              CustomName: _this.flowInstances.CustomName,
              DesignId: _this.flowInstances.DesignId,
              FormData: JSON.stringify(res),
              InstanceResult: t,
              Verifier: userIds
            }
            saveFlowInstancesForUpadate(instance).then(resdata => {
              if (resdata.Msg === 'selfselectionall') {
                _this.selfselection = 'selfselectionall'
                _this.dialogVisible = true
              } else if (resdata.Msg === 'selfselection') {
                _this.selfselection = 'selfselection'
                _this.userSource = resdata.Data
                _this.dialogVisible = true
              } else {
                _this.$message({
                  message: '流程已提交，请等待审核',
                  type: 'success',
                  duration: 3 * 1000
                })
                _this.onCancel()
                _this.$emit('loaddata')
              }
            })
          })
        }
      })
    },
    customVerifiy() {
      var _this = this
      var userIds = []
      _this.selectUser.forEach(item => {
        userIds.push(item.Id)
      })
      if (userIds.length < 1) {
        _this.$message({
          message: '请选择审批人',
          type: 'error',
          duration: 3 * 1000
        })
      }
      var data = { FlowInstanceId: _this.flowInstances.Id, CustomVerifier: userIds }
      customVerifiy(data).then(res => {
        if (res.Msg === 'selfselectionall') {
          _this.selfselection = 'selfselectionall'
          _this.dialogVisible = true
          // _this.instanceId = res.Extend
        } else if (res.Msg === 'selfselection') {
          _this.selfselection = 'selfselection'
          _this.userSource = res.Data
          _this.dialogVisible = true
          // _this.instanceId = res.Extend
        } else {
          _this.$message({
            message: '已提交，请等待审核',
            type: 'success',
            duration: 3 * 1000
          })
          _this.onCancel()
          _this.$emit('loaddata')
        }
      })
    },
    selectApprove() {
      if (this.selfselection === 'selfselectionall') {
        // 选择所有人员
        this.$refs.selectPersonDialog.showSelectPersonDialog()
      } else if (this.selfselection === 'selfselection') {
        this.approverRoleVisible = true
      }
    },
    chooseUser(users) {
      this.selectUser = []
      if (users && users.length > 0) {
        this.selectUser = users
      }
    },
    toggleClass(arr, elem, key = 'id') {
      return arr.some(item => { return item[key] === elem[key] })
    },
    removeEle(arr, elem, key = 'id') {
      var includesIndex
      arr.map((item, index) => {
        if (item[key] === elem[key]) {
          includesIndex = index
        }
      })
      arr.splice(includesIndex, 1)
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table td,::v-deep.el-table th{
  padding:0;
  font-size: 12px;
}
::v-deep.el-table .cell{
  line-height: auto;
}
.avater{
  height: 50px;
  width: 50px;
  border-radius: 50%;

  margin: 10px;
  &:hover{
    box-shadow: 2px 2px 5px #ccc;
    cursor: pointer;
  }

}
</style>
